package com.example.demo.services.impl;

import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.dao.UserMapper;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.User;
import com.example.demo.services.IUserService;
import com.example.demo.utils.MD5Util;
import com.example.demo.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        //非空校验
        if(user ==null
                || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname())
                || StringUtil.isEmpty(user.getPassword()) ){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage().toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }


        //按用户名查询用户
        User existsUser=userMapper.selectByUserName(user.getUsername());
        //判断用户是否存在
        if(existsUser!=null ){
            //打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());

            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }


        //新增用户 设置默认值
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte)0);
        user.setState((byte)0);
        user.setDeleteState((byte)0);
        //日期
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        //写入数据库
        int result=userMapper.insert(user);
        //判断是否成功
        if(result!=1){
            //打印日志
            log.error(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));

        }
        log.info(ResultCode.SUCCESS.toString());


    }

    @Override
    public User selectByUsername(String username) {
        if(StringUtil.isEmpty(username)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }

        //返回查询结果
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //1.参数校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //2.按用户查询信息
        User user=userMapper.selectByUserName(username);
        //3.对查询结果做非空校验
        if( user==null ){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + "username=" + username);
            //  抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }

        //4.对密码做校验
        String encryptedPassword= MD5Util.md5Salt(password, user.getSalt());

        //5.将当前密码与数据库进行对比
        if(!encryptedPassword.equals(user.getPassword())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + "密码错误,username=" + username);
            //  抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        log.info(ResultCode.SUCCESS.toString());
        return user;
    }

    @Override
    public User selectById(Long id) {

        //非空校验
        if(id==null ){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + "id=" + id);
            //  抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //调用dao层查询 获取对象
        User user= userMapper.selectByPrimaryKey(id);

        //返回
        return user;
    }

    @Override
    public void addArticleCountById(Long id) {
        // 非空校验
        if(id==null || id<=0){
            // 日志记录
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        // 查询用户信息
        User user=userMapper.selectByPrimaryKey(id);
        //判断user是否为空
        if(user==null){
            // 日志记录
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户发帖数
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        //更新数据库
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        //判断是否成功
        if(row!=1){
            // 日志记录
            log.error(ResultCode.FAILED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        //非空校验
        if(id==null || id<=0){
            // 日志记录
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        User user=userMapper.selectByPrimaryKey(id);

        if(user==null){
            // 日志记录
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        //新建用户
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);

        if(updateUser.getArticleCount()<0){
            updateUser.setArticleCount(0);
        }

        //更新数据库
        int row=userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }

}
